import React, { useState, useEffect, useContext } from 'react'
import CustomBreadcrumb from '@/components/CustomBreadcrumb'
import { Form, Icon, Button, Input, Radio } from 'antd'
import { withRouter } from 'react-router-dom'
import { requestWrapper } from '@/utils/request'
import userAPI from '@/services/user'
import { useRequest } from 'ahooks'
import GlobalContext from '@/containers/global.context'
import UploadImg from '@/components/UploadImg'
import './styles.scss'

const Set = props => {
    const [path, setPath] = useState(undefined)
    const { me } = useContext(GlobalContext)
    const [visible, setVisible] = useState(0)
    const [count, setCount] = useState(0)
    const [formData, setFormData] = useState({})
    const [tempData, setData] = useState({})
    const { getFieldDecorator } = props.form
    const [canEdit, setCanEdit] = useState(true)
    const [confirmDirty, setConfirmDirty] = useState(false)

    const { run: userUpdate, loading: updateLoading } = useRequest(
        params =>
            requestWrapper(userAPI.userUpdate.bind(null, params), {
                autoSuccess: true,
                errorMessage: '修改失败请稍后再试!'
            }),
        {
            manual: true,
            onSuccess: () => {
                const num = count + 1
                setCount(num)
                setCanEdit(true)
                localStorage.setItem('myInfo', JSON.stringify(tempData))
                window.location.reload()
            }
        }
    )

    const { run: userUpdatePass, loading: updatePassLoading } = useRequest(
        params =>
            requestWrapper(userAPI.userUpdatePass.bind(null, params), {
                autoSuccess: true,
                errorMessage: '原密码错误！'
            }),
        {
            manual: true,
            onSuccess: () => {
                setCanEdit(true)
            }
        }
    )
    const compareToFirstPassword = (rule, value, callback) => {
        const { form } = props
        if (value && value !== form.getFieldValue('newPassword')) {
            callback('输入的两次密码不一致！')
        } else {
            callback()
        }
    }
    const validateToNextPassword = (rule, value, callback) => {
        const { form } = props
        if (value && confirmDirty) {
            form.validateFields(['confirmPassword'], { force: true })
        }
        callback()
    }
    const handleConfirmBlur = e => {
        const { value } = e.target
        setConfirmDirty(confirmDirty || !!value)
        console.log(1)
    }

    const setSubmit = () => {
        props.form.validateFields((err, values) => {
            if (!err) {
                values.age = parseInt(values.age)
                values.sex = parseInt(values.sex)
                values.headImg = path || me.headImg
                values.role = me.role
                values.id = me.id
                values.createTime = me.createTime
                console.log(values)
                setData(values)
                userUpdate(values)
            }
        })
    }

    const setPassword = () => {
        props.form.validateFields((err, values) => {
            if (!err) {
                userUpdatePass({ oldPass: values.password, newPass: values.newPassword })
            }
        })
    }

    useEffect(() => {
        let data = JSON.parse(localStorage.getItem('myInfo'))
        setFormData(data)
        console.log(data)
        props.form.resetFields(formData)
    }, [count])

    return (
        <div className='set'>
            <div>
                <CustomBreadcrumb arr={['用户管理', '个人信息', '个人设置']}></CustomBreadcrumb>
            </div>
            <div className='my_content'>
                <div className='my_left'>
                    <div>
                        <div className='headImg'>
                            <img src={formData.headImg ? formData.headImg : 'assets/boy.jpg'} alt='' />
                        </div>
                        <h2>{formData.username}</h2>
                    </div>
                    <div
                        className='item'
                        onClick={() => {
                            setVisible(0)
                            setCanEdit(true)
                        }}>
                        <Icon type='user' /> <div>个人资料</div>
                    </div>
                    <div
                        className='item'
                        onClick={() => {
                            setVisible(1)
                            setCanEdit(true)
                        }}>
                        <Icon type='paper-clip' /> <div>修改密码</div>
                    </div>
                </div>
                <div className='my_right'>
                    {visible === 0 ? (
                        <div>
                            <h2>基本信息</h2>
                            <Form onSubmit={setSubmit}>
                                <Form.Item label='头像'>
                                    <UploadImg disabled={canEdit} setPath={setPath} />
                                </Form.Item>
                                <Form.Item label='用户名'>
                                    {getFieldDecorator('username', {
                                        initialValue: formData.username
                                    })(<Input disabled={true} />)}
                                </Form.Item>
                                <Form.Item label='性别'>
                                    {getFieldDecorator('sex', {
                                        rules: [{ required: true, message: '请选择性别' }],
                                        initialValue: parseInt(formData.sex)
                                    })(
                                        <Radio.Group disabled={canEdit}>
                                            <Radio value={1}>男</Radio>
                                            <Radio value={2}>女</Radio>
                                        </Radio.Group>
                                    )}
                                </Form.Item>
                                <Form.Item label='年龄'>
                                    {getFieldDecorator('age', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '请输入年龄'
                                            },
                                            { pattern: new RegExp(/^[1-9]\d*$/, 'g'), message: '请输入合法的年龄' }
                                        ],
                                        initialValue: formData.age
                                    })(<Input disabled={canEdit} />)}
                                </Form.Item>
                                <Form.Item label='简介'>
                                    {getFieldDecorator('desc', {
                                        rules: [{ required: false }],
                                        initialValue: formData.desc
                                    })(<Input.TextArea disabled={canEdit} />)}
                                </Form.Item>
                                <Form.Item>
                                    <Button
                                        disabled={canEdit}
                                        type='primary'
                                        htmlType='submit'
                                        className='login-form-button'>
                                        保存修改
                                    </Button>
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    <Button
                                        disabled={!canEdit}
                                        type='primary'
                                        onClick={() => {
                                            setCanEdit(false)
                                        }}>
                                        开始修改
                                    </Button>
                                </Form.Item>
                            </Form>
                        </div>
                    ) : (
                        <div>
                            <h2>修改密码</h2>
                            <Form onSubmit={setPassword}>
                                <Form.Item label='原密码'>
                                    {getFieldDecorator('password', {
                                        rules: [{ required: true, message: '请输入原密码' }]
                                    })(<Input.Password disabled={canEdit} />)}
                                </Form.Item>
                                <Form.Item label='新密码' hasFeedback>
                                    {getFieldDecorator('newPassword', {
                                        rules: [
                                            { required: true, message: '请输入新密码' },
                                            {
                                                validator: validateToNextPassword
                                            },
                                            {
                                                pattern: new RegExp('^[0-9a-zA-Z_]{1,}$', 'g'),
                                                message: '只允许包含数字、字母、下划线'
                                            },
                                            { min: 6, message: '密码不得少于6位' },
                                            { max: 16, message: '密码不能超过16位' }
                                        ]
                                    })(<Input.Password disabled={canEdit} />)}
                                </Form.Item>
                                <Form.Item label='确认密码' hasFeedback>
                                    {getFieldDecorator('confirmPassword', {
                                        rules: [
                                            { required: true, message: '请在此确认密码' },
                                            { validator: compareToFirstPassword },
                                            {
                                                pattern: new RegExp('^[0-9a-zA-Z_]{1,}$', 'g'),
                                                message: '只允许包含数字、字母、下划线'
                                            },
                                            { min: 6, message: '密码不得少于6位' },
                                            { max: 16, message: '密码不能超过16位' }
                                        ]
                                    })(<Input.Password onBlur={handleConfirmBlur} disabled={canEdit} />)}
                                </Form.Item>
                                <Form.Item>
                                    <Button
                                        disabled={canEdit}
                                        type='primary'
                                        htmlType='submit'
                                        className='login-form-button'>
                                        确认修改
                                    </Button>
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    <Button
                                        disabled={!canEdit}
                                        type='primary'
                                        onClick={() => {
                                            setCanEdit(false)
                                        }}>
                                        修改密码
                                    </Button>
                                </Form.Item>
                            </Form>
                        </div>
                    )}
                </div>
            </div>
        </div>
    )
}

export default withRouter(Form.create()(Set))
